﻿/*---------------------------------------------------------------------*/
// fileName="IConfigParameterPresenter.cs" CompanyName="SureKAM"
// Copyright SureKAM (c). All right reserved.
/*---------------------------------------------------------------------*/

using SureKAM.BackUp.Notify.Domain;

namespace SureKAM.BackUp.Notify.Presenter
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using SureKAM.BackUp.Notify.Presenter.Interfaces;
    using SureKAM.BackUp.Notify.Presenter.ViewInterfaces;
    using SureKAM.BackUp.Notify.Service.Interfaces;
    using SureKAM.BackUp.Notify.Common;

    public class ConfigParameterPresenter : IConfigParameterPresenter
    {
        #region 私有字段
        private IConfigParameterView configParameterView;
        private IDirectoryService directoryService;
        private INotifyService notifyService;
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="configParameterView">IConfigParameterView对象</param>
        /// <param name="directoryService">IDirectoryService 对象</param>
        /// <param name="notifyService">INotifyService 对象</param>
        public ConfigParameterPresenter(IConfigParameterView configParameterView, IDirectoryService directoryService, INotifyService notifyService)
        {
            this.configParameterView = configParameterView;
            this.directoryService = directoryService;
            this.notifyService = notifyService;
        }
        #endregion

        #region 私有方法
        List<Domain.Notify> GetNotifys(string id)
        {
            Domain.Directory directory = this.directoryService.GetDirectoryById(id);
            List<Domain.Notify> notifies = directory.Notifys;
            return notifies;
        }

        void updateDNMapping(string id, List<Domain.Notify> notifies)
        {
            Domain.Directory directory = this.directoryService.GetDirectoryById(id);
            if (directory != null)
            {
                List<Domain.Notify> notifys = directory.Notifys;
                if (notifies != null && notifies.Count > 0)
                {
                    if (notifys == null)
                    {
                        foreach (Domain.Notify notify in notifies)
                        {
                            this.directoryService.AddDNMapping(id, notify.ID);
                        }
                    }
                    else
                    {
                        foreach (var notify in notifies)
                        {
                            var temp = from notify1 in notifys where notify1.ID == notify.ID select notify1;
                            if (temp != null && temp.Count() == 0)
                            {
                                this.directoryService.AddDNMapping(id, notify.ID);
                            }
                        }
                        foreach (var notify in notifys)
                        {
                            var temp = from notify1 in notifies where notify1.ID == notify.ID select notify1;
                            if (temp != null && temp.Count() == 0)
                            {
                                this.directoryService.DeleteDNMapping(id, notify.ID);
                            }
                        }
                    }//end if(notifys)
                }
                else
                {
                    foreach (var notify in notifys)
                    {
                        this.directoryService.DeleteDNMapping(id, notify.ID);
                    }
                }//end if(notifies)
            }
        }

        /// <summary>
        /// 监控
        /// </summary>
        private void StartMonitoting()
        {
            List<Domain.Directory> directories = this.directoryService.GetDirectories();
            if (directories != null)
            {
                foreach (Directory directory in directories)
                {
                    if (!string.IsNullOrEmpty(directory.Address)) ThreadCommon.CreateThread(directory);
                }
            }
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        private void StopMonitoring()
        {
            ThreadCommon.StopThread();
            List<Domain.Directory> directories = ThreadCommon.Directories;
            if (directories != null && directories.Count > 0)
            {
                foreach (Directory directory in directories)
                {
                    this.directoryService.Update(directory);
                }
            }
        }

        private List<string> GetLog()
        {
            string str = LogCommon.Read();
            List<string> stringList = null;
            if (!string.IsNullOrEmpty(str))
            {
                string splitStr = "\r\n";
                string[] strings = str.Split(splitStr.ToCharArray());
                if (strings.Count() > 0)
                    stringList = (from s in strings where !string.IsNullOrEmpty(s) select s).ToList();
            }
            return stringList;
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        private void sendMail()
        {
            string EmailServer = System.Configuration.ConfigurationSettings.AppSettings["EmailServer"].ToString();
            string EmailUser = System.Configuration.ConfigurationSettings.AppSettings["EmailUser"].ToString();
            string EmailPassword = System.Configuration.ConfigurationSettings.AppSettings["EmailPassword"].ToString();
            string adminEmail = System.Configuration.ConfigurationSettings.AppSettings["adminEmail"].ToString();
            List<Domain.Directory> directories = this.directoryService.GetDirectories();
            List<string> strings = this.GetLog();

            if (directories != null)
            {
                foreach (Directory directory in directories)
                {
                    if (directory.Notifys != null && directory.Notifys.Count > 0)
                    {
                        string toMail = null;
                        foreach (Domain.Notify notify in directory.Notifys)
                        {
                            if (!string.IsNullOrEmpty(notify.Email)) toMail += (notify.Email + ";");
                        }
                        if (string.IsNullOrEmpty(toMail)) break;
                        else
                        {
                            if (toMail.IndexOf(';') > 0) toMail = toMail.Substring(0, toMail.LastIndexOf(';'));
                        }
                        if (strings == null || strings.Count <= 0)
                        {
                            MailCommon mailCommon = new MailCommon(EmailServer, 25, adminEmail, toMail, "服务器数据备份失败", "服务器数据备份失败请与管理员联系!", EmailUser, EmailPassword);
                            if (mailCommon.send()) LogCommon.Clear();
                            continue;

                        }
                        else
                        {
                            var reslu =
                                from s in strings where s.IndexOf("[" + directory.BackUpServer + "]") >= 0 select s;
                            if (reslu != null && reslu.Count() > 0)
                            {
                                List<string> strs = reslu.ToList();
                                string content = null;
                                content = content + "服务器名称:" + directory.BackUpServer + "<br/>";
                                content = content + "备份状态:成功<br>";
                                content = content + "服务器备份配额：" +directory.MaxSize.ToString() + "MB<br/>";
                                if(directory.RealSize>=0)
                                {
                                    content = content + "服务器备份已用空间：" + directory.RealSize.ToString() + "MB<br/>";
                                }
                                foreach (string str in strs)
                                {
                                    content += (str + "<br />");
                                }
                                MailCommon mailCommon = new MailCommon(EmailServer, 25, adminEmail, toMail, "服务器数据备份成功", content, EmailUser, EmailPassword);
                                if (mailCommon.send()) LogCommon.Clear();
                                continue;

                            }
                            else
                            {
                                MailCommon mailCommon = new MailCommon(EmailServer, 25, adminEmail, toMail, "服务器数据备份失败", "服务器数据备份失败请与管理员联系!", EmailUser, EmailPassword);
                                if (mailCommon.send()) LogCommon.Clear();
                            }
                        }
                    }
                }
            }


        }
        #endregion

        #region 公有方法
        /// <summary>
        /// 初始方法
        /// </summary>
        public void Init()
        {
            this.configParameterView.changeSelectDirectory = GetNotifys;
            this.configParameterView.updateDNMapping = updateDNMapping;
            this.configParameterView.DatabindDirectory(this.directoryService.GetDirectories());
            this.configParameterView.DataBindNotifys(this.notifyService.GetNotifies());
            this.configParameterView.monitoring = StartMonitoting;
            this.configParameterView.stopMonitoring = StopMonitoring;
            this.configParameterView.getLog = GetLog;
            this.configParameterView.mailSend = sendMail;
        }
        #endregion
    }
}
